﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PServiceBus.Services.Gateway.Runtime;
using PServiceBus.Gateway.Interfaces.DTO;

namespace PServiceBus.Services.Gateway.Extensions {
    public static partial class SubscriberExtension {
        public static Subscriber ToSubscriber(this SubscriberInfo subscriberInfo) {
            if (subscriberInfo == null) return null;
            if (!subscriberInfo.IsValid)
                return Subscriber.New(subscriberInfo.Name).Valid(subscriberInfo.IsValid);
            var subscriber =
                Subscriber.New(subscriberInfo.Name)
                .Durable(subscriberInfo.Durable)
                .Id(subscriberInfo.ID);
            foreach (var topic in subscriberInfo.Topics)
                subscriber.SubscribeTo(topic.Value.ToTopic());
            foreach (var kv in subscriberInfo.Transports) {
                var transport = kv.Value;
                subscriber.AddTransport(transport.Name, transport.Transport,
                    transport.TopicName);
            }
            subscriber._actions.Clear();
            return subscriber;
        }

        public static SubscriberInfo ToSubscriberInfo(this Subscriber subscriber) {
            return new SubscriberInfo()
            {
                Durable = subscriber.IsSubscriberDurable,
                ID = subscriber.SubscriberID,
                Name = subscriber.SubscriberName,
                IsValid = subscriber.IsValid,
                Topics = subscriber.Topics
                    .ToDictionary(kv => kv.Key, kv => kv.Value.ToTopicInfo()),
                Transports = subscriber.Transports.ToDictionary(kv => kv.Key, kv => kv.Value)
            };
        }
    }
}
